package updown.controller.other;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import updown.domain.Log;
import updown.domain.ResultVo;
import updown.service.task.LogService;
import updown.util.DateUtils;
import updown.util.ServerContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 基础Controller
 */
@Controller
@Slf4j
public class BaseController {

	@Autowired
	private LogService logService;

	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	public static HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	}
	
	public static ResultVo writeToSuccess(Object object){
		ResultVo resultVo = new ResultVo();
		resultVo.setRetCode(1);
		resultVo.setMsg("success");
		resultVo.setData(object);
		log.info(resultVo.toString());
		return resultVo;
	}
	
	public static ResultVo writeToSuccess(){
		return writeToSuccess(null);
	}
	
	public static ResultVo writeToFail(Object object){
		HttpServletResponse response = getResponse();
		response.setStatus(HttpStatus.BAD_REQUEST.value());
		
		ResultVo resultVo = new ResultVo();
		resultVo.setRetCode(0);
		resultVo.setMsg("fail");
		resultVo.setData(object);
		log.info(resultVo.toString());
		return resultVo;
	}
	
	public static ResultVo writeToFail(){
		HttpServletResponse response = getResponse();
		response.setStatus(HttpStatus.BAD_REQUEST.value());
		return writeToFail(null);
	}

	public void addLog(String description,String moduleName){
		String userName = ServerContextHolder.getContext().getUserName();
		addLog(userName, description,moduleName);
	}

	public void addLog(String userName,String description,String moduleName){
		Log superLog = new Log();
		superLog.setOperatorName(userName);
		superLog.setOperateDescription(description);
		superLog.setOperateModule(moduleName);
		superLog.setOperateTime(DateUtils.getCurDateTime());
		logService.add(superLog);
	}
}
